package com.onlinevideo.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


public class JdbcUtils {

    private static DruidDataSource dataSource  = new DruidDataSource();
    static {
        String path = "jdbc.properties";
        Properties properties = new Properties();
        try {
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream(path));
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        }catch (IOException e){
            System.out.println("配置文件【" +path + "】没有找到");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取数据库连接池中的连接
     *
     * @return 如果返回null 说明获取连接失败 有值就是获取连接成功
     */
    public static Connection getConnection() {
        Connection con = null;
        try {
            con = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * @description 关闭连接 放回数据库连接池
     * @param con
     */
    public static void close(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
